﻿#include "con_produce_dialog.h"
#include "ui_con_produce_dialog.h"
#include "purchase_dialog.h"
//超市商品管理界面
con_produce_dialog::con_produce_dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::con_produce_dialog)
{
    ui->setupUi(this);
}

con_produce_dialog::~con_produce_dialog()
{
    delete ui;
}

//显示所有商品
void con_produce_dialog::showEvent(QShowEvent *)
{
    sqlite3 *pDb;
    if(sqlite3_open("./supermarket.db", &pDb) == SQLITE_OK){
        QString sql = "select * from produce order by p_num DESC;";
        sqlite3_stmt *pStmt;
        if(sqlite3_prepare(pDb, sql.toStdString().c_str(), sql.length(), &pStmt, NULL) == SQLITE_OK){
            while(sqlite3_step(pStmt) == SQLITE_ROW){
                const unsigned char *pId = sqlite3_column_text(pStmt, 0);
                const unsigned char *pName = sqlite3_column_text(pStmt, 1);
                const unsigned char *pGetPrice = sqlite3_column_text(pStmt, 2);
                const unsigned char *psellPrice = sqlite3_column_text(pStmt, 3);
                const unsigned char *pNum = sqlite3_column_text(pStmt, 4);

                QTableWidgetItem *pIdItem = new QTableWidgetItem((char *)pId);
                QTableWidgetItem *pNameItem = new QTableWidgetItem((char *)pName);
                QTableWidgetItem *pGetPriceItem = new QTableWidgetItem((char *)pGetPrice);
                QTableWidgetItem *psellPriceItem = new QTableWidgetItem((char *)psellPrice);
                QTableWidgetItem *pNumItem = new QTableWidgetItem((char *)pNum);

                ui->conProWidget->insertRow(0);

                ui->conProWidget->setItem(0, 0, pIdItem);
                ui->conProWidget->setItem(0, 1, pNameItem);
                ui->conProWidget->setItem(0, 2, pGetPriceItem);
                ui->conProWidget->setItem(0, 3, psellPriceItem);
                ui->conProWidget->setItem(0, 4, pNumItem);
            }
        }
    }
}

//删除表格中的数据（操作数据库）
void con_produce_dialog::on_delProBtn_clicked()
{
    int row = ui->conProWidget->currentRow();
    if(row >= 0) {
        QTableWidgetItem *pIdItem = ui->conProWidget->item(row, 0);
                 QString pid = pIdItem->text();
                 sqlite3 *pDb;
                 if(sqlite3_open("./supermarket.db", &pDb) != SQLITE_OK) return;
                 QString sql = "delete from produce where p_id='" +pid+ "';";
                 char *errmsg;
                 if(sqlite3_exec(pDb,sql.toStdString().c_str(), NULL, NULL, &errmsg) == SQLITE_OK){
                     ui->conProWidget->removeRow(row);
                 }
                 sqlite3_close(pDb);
    }
}

void con_produce_dialog::on_delProBtn_2_clicked()
{
    this->close();
    purchase_dialog *purchase = new purchase_dialog();
    purchase->exec();

}
